# -*- coding: utf-8 -*-
# @Author : y
# @Date   : 2021/6/15
# @File   : EG49_Ent5yearsEnvirDefaultCnt.py
# @E-mail : yantao@bbdservice.com

'''eof
name:申请企业近五年被列入环保失信名单次数
code:EG49_Ent5yearsEnvirDefaultCnt
tableName:
columnName:
groups:企业通用模块
dependencies:FGW_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''
import sys
import pandas as pd
import json
from datetime import datetime


def format_data(tableName):
    try:
        eg = FGW_DSJ.get("data").get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


def get_date_list():
    try:
        now = datetime.now()
        aaa = [(now + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-60, 0]]
        return aaa
    except:
        return None


def get_result():
    '''
    申请企业信用评定日期在近五年内且为环保失信等级的次数
    Factor1=信用评价最低等级（stClCreditLevelInfoD）中环境信用等级（evrmCreditGrade）取值为“环保领域严重失信生产者”
    Factor=count(Factor1)
    '''
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    incp_case = '环保领域严重失信生产者'
    try:
        alter_list = format_data("stClCreditLevelInfoD")
        date_list = get_date_list()
        if alter_list == [{}]:
            return u'缺失值'
        else:
            if len(alter_list) >= 1:
                factor = []
                for i in alter_list:
                    assess_time = i.get("assessTime")
                    evrm_credit_grade = i.get("evrmCreditGrade")
                    if evrm_credit_grade not in null_type_list and \
                            assess_time not in null_type_list and \
                            len(assess_time) >= 4 and \
                            assess_time[0:4].isdigit() and not assess_time.startswith("0"):
                        if incp_case == evrm_credit_grade and date_list[0][0:4] < assess_time[0:4] <= date_list[1][0:4]:
                            factor.append(1)
                        else:
                            factor.append(0)
                return sum(factor) if len(factor) > 0 else u'缺失值'
            else:
                return 0
    except:
        return u'缺失值'


if __name__ == "__main__":
    # file_obj = open(r'../data/DAS/Past3YearPatentedInventionsNum/FGW_DSJ.json', encoding='utf-8', mode='r')
    file_obj = open(r'FGW_DSJ.json', encoding='utf-8', mode='r')
    content = file_obj.read()
    FGW_DSJ = json.loads(content, strict=False)
    aa = get_result()
    print(aa)

result = get_result()
